package com.tianji.learning.listener;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.LEARNING_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;

import static com.tianji.common.constants.MqConstants.Queue.LEARNING_LESSON_PAY_QUEUE;

@Slf4j
@Component
public class mqLessonChangeListener {

    @Autowired
    private ILearningLessonService lessonService;


    /**
     *监听购买课程后的消息
     * @param orderBasicDTO
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = LEARNING_LESSON_PAY_QUEUE,durable = "true"),
            exchange = @Exchange(name = LEARNING_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listenLessonAddChange(OrderBasicDTO orderBasicDTO){
        if (ObjectUtil.isEmpty(orderBasicDTO)){
            log.error("mq消息监听发生错误,订单或者报名课程数据为空");
            return;
        }
        log.info("收到了消息,购买用户的id:{},以及购买课程的ids:{}",orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
        lessonService.addMyLessonsByCourseIds(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }

    /**
     *监听退款课程后的消息
     * @param orderBasicDTO
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.LEARNING_LESSON_REFUND_QUEUE,durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonRefuseChange(OrderBasicDTO orderBasicDTO){
        if (ObjectUtil.isEmpty(orderBasicDTO)){
            log.error("mq消息监听发生错误,订单或者报名课程数据为空");
            return;
        }
        log.info("收到了消息,退款用户的id:{},以及退款课程的ids:{}",orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
        lessonService.deleteMyLessonsByCourseIds(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }


}
